package com.xu.springboot04.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

// @Configuration
public class MyDataSourceConfig {

    // 默认的自动配置是判断容器中没有数据源才会配置 @ConditionalOnMissingBean(DataSource.class)
    // 可以将 application.yaml 中默认的 hikari 数据源的配置赋值给 druid 数据源
//    @Bean
//    @ConfigurationProperties("spring.datasource")
    public DataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        // 加入监控功能
        dataSource.setFilters("stat,wall");
        return dataSource;
    }

    /**
     * 配置 druid 的监控页功能
     */
//    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet(){
        StatViewServlet servlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(servlet, "/druid/*");
        bean.addInitParameter("loginUsername", "admin");
        bean.addInitParameter("loginPassword", "123");
        return bean;
    }

    /**
     * WebStatFilter 用于采集 web-jdbc 关联监控的数据
     */
//    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter(){
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> filter = new FilterRegistrationBean<>(webStatFilter);
        filter.setUrlPatterns(Arrays.asList("/*"));
        filter.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

        return filter;
    }

}
